package com.copera.cn.kaka;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.http.client.ClientProtocolException;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.ActivityNotFoundException;
import android.content.ContentResolver;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.Bitmap.Config;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.graphics.drawable.BitmapDrawable;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.provider.MediaStore;
import android.util.DisplayMetrics;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;

import com.copera.cn.kaka.picpopupwindow.SelectPicPopupWindow;
import com.copera.cn.kaka.util.ActionUrls;
import com.copera.cn.kaka.util.HttpUtils;
import com.copera.cn.kaka.util.JsonUtil;
import com.copera.cn.kaka.util.Options;
import com.copera.cn.kaka.util.UploadUtil;
import com.copera.cn.kaka.util.Utility;
import com.copera.cn.kaka.vo.ExchangeRuleVo;
import com.copera.cn.kaka.vo.ImageSetVo;
import com.copera.cn.kaka.vo.ImageVO;
import com.copera.cn.kaka.vo.ShopVo;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.listener.SimpleImageLoadingListener;

public class MainActivity extends BaseActivity {

	private RelativeLayout rl;//兑换礼品
	private RelativeLayout trackRL;//足迹
	private RelativeLayout photoRL,photoRL1,photoRL2;//拍照
	private TextView ms_text1,ms_text2,ms_tv7,ms_tv10,ms_tv13,ms_tv16,img_01,ms_tv18;
	public static final int SELECT_PIC_BY_PICK_PHOTO = 2;
	private ApplicationCustomer appc;
	private Button ms_btset;
	private String shopId;
	private int num = 0;
	private RelativeLayout track,exchange;
	// 自定义的弹出框类
    private SelectPicPopupWindow menuWindow;
    private File picFile;
    private final int activity_result_camara_with_data = 1006;
	private final int activity_result_cropimage_with_data = 1007;
	private Uri photoUri1;
	private Bitmap logoBitmap,shopBitmap;
	private List<ImageSetVo> listSet = new ArrayList<ImageSetVo>();
	//活动图片
	private TextView tv_01,tv_02,tv_03,tv_04;
	private ImageView imgset_01,imgset_02,imgset_03,imgset_04;
	
	private int displayWidth;//屏幕宽度
	private Handler mHandler;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.welcome);
	
		initViews();
		initEvent();
		//强制为竖屏 
		setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
		appc = (ApplicationCustomer) getApplication();
		
	}
	private void initViews(){
		track = (RelativeLayout)findViewById(R.id.track);
		exchange = (RelativeLayout)findViewById(R.id.exchange);
		rl = (RelativeLayout)findViewById(R.id.ms_rl27);
	    trackRL = (RelativeLayout)findViewById(R.id.ms_rl26);
	    photoRL = (RelativeLayout)findViewById(R.id.ms_rl30);
	    ms_btset = (Button)findViewById(R.id.ms_btset);
	    ms_text1 = (TextView)findViewById(R.id.ms_text1);
	    ms_text2 = (TextView)findViewById(R.id.ms_text2);
	    ms_tv7 = (TextView)findViewById(R.id.ms_tv7);
	    ms_tv10 = (TextView)findViewById(R.id.ms_tv10);
	    ms_tv13 = (TextView)findViewById(R.id.ms_tv13);
	    ms_tv16 = (TextView)findViewById(R.id.ms_tv16);
	    img_01 = (TextView)findViewById(R.id.img_01);
	    photoRL1 = (RelativeLayout)findViewById(R.id.ms_rl2);
	    photoRL2 = (RelativeLayout)findViewById(R.id.ms_rl31);
	   
        tv_01 = (TextView)findViewById(R.id.tv_01);
        imgset_01 = (ImageView)findViewById(R.id.imgset_01);
        tv_02 = (TextView)findViewById(R.id.tv_02);
        imgset_02 = (ImageView)findViewById(R.id.imgset_02);
        tv_03 = (TextView)findViewById(R.id.tv_03);
        imgset_03 = (ImageView)findViewById(R.id.imgset_03);
        tv_04 = (TextView)findViewById(R.id.tv_04);
        imgset_04 = (ImageView)findViewById(R.id.imgset_04);
        mHandler = new Handler();
       
       
	}
	//兑换规则
	private void initSet(){
		List<Map<String,Object>> listItems = new ArrayList<Map<String,Object>>();
		ShopVo shop = appc.getShop();
		if(shop!=null){
			List<ExchangeRuleVo> list = shop.getRuleList();
			Map<String,Object> listItem;
			if (list != null) {
				for (ExchangeRuleVo er : list) {
					listItem = new HashMap<String,Object>();
					listItem.put("content", er.getPointCount()+"卡点兑换"+er.getExchangeContent());
				    listItems.add(listItem);
				}
				SimpleAdapter simpleAdapter = new SimpleAdapter(this
		                , listItems
		                , R.layout.shop_rule_list
		                , new String[]{"content"}
		                , new int[]{R.id.ms_tv3});
		        ListView listView = (ListView)findViewById(R.id.rule_list);
				listView.setAdapter(simpleAdapter);
				setListViewHeightBasedOnChildren(listView);
			}
		}
		
	}
	private void initValues(){
		ShopVo shop = appc.getShop();
		ms_text1.setText(getValue("shopName"));
		ms_text2.setText(getValue("address"));
		ms_tv7.setText(shop.getTrackToday());
		ms_tv10.setText(shop.getExchangeToday());
		ms_tv13.setText(shop.getPraiseCount());
		ms_tv16.setText(shop.getShareCount());
		shopId = getValue("shopId");
	}
	private void initEvent(){
		track.setOnClickListener(new View.OnClickListener() {
			public void onClick(View v) {
				if(logoBitmap !=null && !logoBitmap.isRecycled()){
					 logoBitmap.recycle();
					 logoBitmap = null;
		        }
				Intent intent = new Intent(MainActivity.this,MipcaActivityCapture.class);
				Bundle bundle = new Bundle();
				bundle.putString("type", "track");
				intent.putExtras(bundle);
			    startActivity(intent);
			    finish();
				
				
			}
		});
		exchange.setOnClickListener(new View.OnClickListener() {
			public void onClick(View v) {
				Intent intent = new Intent(MainActivity.this,MipcaActivityCapture.class);
				Bundle bundle = new Bundle();
				bundle.putString("type", "rule");
				intent.putExtras(bundle);
			    startActivity(intent);
				
				
			}
		});
		rl.setOnClickListener(new View.OnClickListener() {
			public void onClick(View v) {
				Intent intent = new Intent(MainActivity.this,MyShopTableHostActivity.class);
			    startActivity(intent);
			}
		});
        trackRL.setOnClickListener(new View.OnClickListener() {
			public void onClick(View v) {
				Intent intent = new Intent(MainActivity.this,MyShopTrackTableHostActivity.class);
			    startActivity(intent);
			}
		});
        ms_btset.setOnClickListener(new View.OnClickListener() {
			public void onClick(View v) {
				//recycle();
				Intent intent = new Intent(MainActivity.this,ShopSetHomeActivity.class);
			    startActivity(intent);
			}
		});
        photoRL.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				// 实例化SelectPicPopupWindow
				menuWindow = new SelectPicPopupWindow(MainActivity.this,itemsOnClick);
				// 显示窗口
				menuWindow.showAtLocation(
						findViewById(R.id.main),
						Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL, 0, 0); // 设置layout在PopupWindow中显示的位置 

			}
		});
	}

	//清楚Bitmap缓存
	private void recycle1(){
		if (logoBitmap != null) {
			logoBitmap.recycle();
		}
		if (shopBitmap != null) {
			shopBitmap.recycle();
		}
		for (ImageSetVo imgvo : listSet ) {
			if (imgvo.getBp() != null) {
				imgvo.getBp().recycle();
			}
		}
	}
	
	//private Uri photoUri;
	private String picPath;
	private void doPhoto(int requestCode, Intent data) {

		if (requestCode == SELECT_PIC_BY_PICK_PHOTO) // 从相册取图片，有些手机有异常情况，请注意
		{
			if (data == null) {
				Toast.makeText(MainActivity.this, "选择图片文件出错", Toast.LENGTH_LONG).show();
				return;
			}
			photoUri1 = data.getData();
			if (photoUri1 == null) {
				Toast.makeText(MainActivity.this, "选择图片文件出错", Toast.LENGTH_LONG).show();
				return;
			}
		}
		String[] pojo = { MediaStore.Images.Media.DATA };

		//Cursor cursor = managedQuery(photoUri, pojo, null, null, null);
		ContentResolver cr = getContentResolver();
		Cursor cursor=cr.query(photoUri1, pojo, null, null, null);
		if (cursor != null) {
			int columnIndex = cursor.getColumnIndexOrThrow(pojo[0]);
			cursor.moveToFirst();
			picPath = cursor.getString(columnIndex);
			cursor.close();
		}

		if (picPath != null
				&& (picPath.endsWith(".png") || picPath.endsWith(".PNG")
						|| picPath.endsWith(".jpg") || picPath.endsWith(".JPG"))) {
			
			File file = null;
			try {
				BitmapFactory.Options opts = new BitmapFactory.Options();
				opts.inJustDecodeBounds = true;
				BitmapFactory.decodeFile(picPath, opts);
				File f = new File(picPath);
				if(f.length()/1024<100){
					opts.inSampleSize = 1;
				}else{
					opts.inSampleSize = Utility.getinSampleSize(opts);
				}
                opts.inJustDecodeBounds = false;
                int jd = Utility.readPictureDegree(picPath);
                Bitmap bp = BitmapFactory.decodeFile(picPath, opts);
				bp = UploadUtil.rotaingImageView(jd, bp);
				DisplayMetrics dm = new DisplayMetrics();
				 getWindowManager().getDefaultDisplay().getMetrics(dm);
				 displayWidth = dm.widthPixels;
				 file = UploadUtil.saveMyBitmap(bp);
				 bp = Utility.getimage(file.getAbsolutePath());
				 bp=Utility.change(bp, displayWidth);
				 BitmapDrawable bd = new BitmapDrawable(bp);
				 photoRL.setBackgroundDrawable(bd);
				 photoRL1.setVisibility(View.GONE);
				 photoRL2.setVisibility(View.GONE);
				 upload(Utility.small(bp));
				
			} catch (IOException e) {
				
				e.printStackTrace();
			}
			

		} else {
			Toast.makeText(MainActivity.this, "选择图片文件不正确", Toast.LENGTH_LONG).show();
		}
	}
    
	@Override
	protected void onResume() {
		initPraiseOrShare();
		loadLogomage();
		loadSetData();
		initValues();
		initLoadImage();
		initSet();
		
		super.onResume();
	}
	
	public void onActivityResult1(int requestCode, int resultCode, Intent data) {
		 if (resultCode == 10) { 
			 
				BitmapDrawable bd = new BitmapDrawable(Utility.small(appc.getBmImage()));
			 photoRL.setBackgroundDrawable(bd);
			 photoRL1.setVisibility(View.GONE);
			 photoRL2.setVisibility(View.GONE);
			 upload(appc.getBmystp());
		 }else if (resultCode == Activity.RESULT_OK) {
				doPhoto(requestCode, data);
				
			}
		super.onActivityResult(requestCode, resultCode, data);
		
		
		
		
	}
    public void upload(String picturePath){
    	BitmapFactory.Options opts = new BitmapFactory.Options();
		opts.inJustDecodeBounds = true;
		BitmapFactory.decodeFile(picturePath, opts);
		             
		opts.inSampleSize = Utility.computeSampleSize(opts, -1, 128*128);       
		opts.inJustDecodeBounds = false;

		UploadUtil uploadUtil = UploadUtil.getInstance();
		File file= null;
		
		try {
			file = UploadUtil.saveMyBitmap(BitmapFactory.decodeFile(picturePath, opts));
		} catch (IOException e) {
		
			e.printStackTrace();
		}

		Map<String, String> params = new HashMap<String, String>();
		params.put("shopId", shopId);
		params.put("type","");
		params.put("flag","shop_img");
		uploadUtil.uploadFile(file.getAbsolutePath(), "pic",ActionUrls.URL_UPLOAD, params);
		try {
			Thread.sleep(600);
		} catch (InterruptedException e) {
			e.printStackTrace();
		} 
		loadImage();
    }
	

	@Override
	public void onDestroy() {
		 if(logoBitmap !=null && !logoBitmap.isRecycled()){
			 logoBitmap.recycle();
			 logoBitmap = null;
     }
		super.onDestroy();
	}
	// 为弹出窗口实现监听类
	private OnClickListener itemsOnClick = new OnClickListener() {

		public void onClick(View v) {
			menuWindow.dismiss();
			
			int id = v.getId();
			if (id == R.id.btn_take_photo) {
				
				String status = Environment.getExternalStorageState();
				if (status.equals(Environment.MEDIA_MOUNTED)) {// 判断是否有SD卡
					doTakePhoto();// 用户点击了从照相机获取
				}
			} else if (id == R.id.btn_pick_photo) {
				
				doCropPhoto();// 从相册中去获取
			} else {
				//finish();
			}

		}
	};	
	/**
	 * 拍照获取图片
	 * 
	 */
	protected void doTakePhoto() {
		try {
			File uploadFileDir = new File(Environment.getExternalStorageDirectory(), "/upload");
			Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
			if (!uploadFileDir.exists()) {
				uploadFileDir.mkdirs();
			}
			picFile = new File(uploadFileDir, "upload.jpeg");
			if (!picFile.exists()) {
				picFile.createNewFile();
			}
			photoUri1 = Uri.fromFile(picFile);
			cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, photoUri1);
			startActivityForResult(cameraIntent, activity_result_camara_with_data);
		} catch (ActivityNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	protected void doCropPhoto() {
		try {
			File pictureFileDir = new File(Environment.getExternalStorageDirectory(), "/upload");
			if (!pictureFileDir.exists()) {
				pictureFileDir.mkdirs();
			}
			picFile = new File(pictureFileDir, "upload.jpeg");
			if (!picFile.exists()) {
				picFile.createNewFile();
			}
			photoUri1 = Uri.fromFile(picFile);
			final Intent intent = getCropImageIntent();
			startActivityForResult(intent, activity_result_cropimage_with_data);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	/**
	 * Constructs an intent for image cropping. 调用图片剪辑程序
	 */
	public Intent getCropImageIntent() {
		Intent intent = new Intent(Intent.ACTION_GET_CONTENT, null);
		intent.setType("image/*");
		intent.putExtra("crop", "true");
		intent.putExtra("aspectX", 1.6);
		intent.putExtra("aspectY", 1);
		intent.putExtra("outputX", 400);
		intent.putExtra("outputY", 400);
		intent.putExtra("noFaceDetection", true);
		
		
		
		intent.putExtra("scale", true);
         intent.putExtra("scaleUpIfNeeded", true);
         intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(picFile));
         intent.putExtra("outputFormat", Bitmap.CompressFormat.JPEG.toString());
		return intent;
	}
	private void cropImageUriByTakePhoto() {
		 Intent intent = new Intent("com.android.camera.action.CROP");
		 intent.setDataAndType(photoUri1, "image/*");
		 intent.putExtra("crop", "true");
		 intent.putExtra("aspectX", 1.6);
		 intent.putExtra("aspectY", 1);
		 intent.putExtra("outputX", 400);
		 intent.putExtra("outputY", 400);
		 intent.putExtra("scale", true);
         intent.putExtra("scaleUpIfNeeded", true);
         intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(picFile));
		
		 intent.putExtra("outputFormat", Bitmap.CompressFormat.JPEG.toString());
		 intent.putExtra("noFaceDetection", true); // no face detection
		 startActivityForResult(intent, activity_result_cropimage_with_data);
	}
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		switch (requestCode) {
		case activity_result_camara_with_data: // 拍照
			try {
				cropImageUriByTakePhoto();
			} catch (Exception e) {
				e.printStackTrace();
			}
			break;
		case activity_result_cropimage_with_data:
				try {
					if (photoUri1 != null&&data!=null) {
						
						Bitmap bitmap = decodeUriAsBitmap(photoUri1);
						DisplayMetrics dm = new DisplayMetrics();
						getWindowManager().getDefaultDisplay().getMetrics(dm);
						int displayWidth = dm.widthPixels;
						bitmap=change(bitmap, displayWidth);
						BitmapDrawable bd = new BitmapDrawable(bitmap);
						photoRL.setBackgroundDrawable(bd);
						photoRL1.setVisibility(View.GONE);
						photoRL2.setVisibility(View.GONE);
						
						upload(bitmap);
					}
				} catch (Exception e) {
					e.printStackTrace();
				}
			break;
		}
	}
	
	private Bitmap decodeUriAsBitmap(Uri uri) {
		Bitmap bitmap = null;
		try {
			bitmap = BitmapFactory.decodeStream(getContentResolver().openInputStream(uri));
		} catch (FileNotFoundException e) {
			e.printStackTrace();
			return null;
		}
		return bitmap;
	}
	
	public void upload(Bitmap bitmap) {
		

		UploadUtil uploadUtil = UploadUtil.getInstance();
		File file = null;

		try {
			file = UploadUtil.saveMyBitmap(bitmap);
		} catch (IOException e) {

			e.printStackTrace();
		}

		Map<String, String> params = new HashMap<String, String>();
		params.put("shopId", shopId);
		params.put("type","");
		params.put("flag","shop_img");
		uploadUtil.uploadFile(file.getAbsolutePath(), "pic",ActionUrls.URL_UPLOAD, params);
		try {
			Thread.sleep(600);
		} catch (InterruptedException e) {
			e.printStackTrace();
		} 
		loadImage();
	}
    public void setListViewHeightBasedOnChildren(ListView listView) {   
    	
    	// 获取ListView对应的Adapter   
        ListAdapter listAdapter = listView.getAdapter();   
        if (listAdapter == null) {   
            return;   
        }   
    	   
    	int totalHeight = 0;   
    	for (int i = 0, len = listAdapter.getCount(); i < len; i++) {   
    		// listAdapter.getCount()返回数据项的数目   
	        View listItem = listAdapter.getView(i, null, listView);   
	        // 计算子项View 的宽高   
	        listItem.measure(0, 0);    
	        // 统计所有子项的总高度   
	        totalHeight += listItem.getMeasuredHeight();    
	    }          
       
        ViewGroup.LayoutParams params = listView.getLayoutParams();   
    	    params.height = totalHeight+ (listView.getDividerHeight() * (listAdapter.getCount() - 1));   
    	    // listView.getDividerHeight()获取子项间分隔符占用的高度   
    	    // params.height最后得到整个ListView完整显示需要的高度   
    	    listView.setLayoutParams(params);   
    } 
  //加载图片
  	private void loadImage() {
  		new AsyncTask<String, Integer, BitmapDrawable>() {
  			@SuppressWarnings("deprecation")
			@Override
  			protected  BitmapDrawable doInBackground(String... params) {
  				BitmapDrawable bd;
  				try {
  					String url = ActionUrls.URL_SHOP_IMG + "?shopId="+shopId;
  					String json = HttpUtils.get(url, getAppCustomer().getHttpClient());
  					JSONObject jo = new JSONObject(json);
  					JSONObject jsonObject = jo.getJSONObject("shopImage");
  					bd = new BitmapDrawable(Utility.small(getPic(ActionUrls.HOST_IMG+jsonObject.getString("fileName"))));
  					return bd;
  				} catch (Exception e) {
  					e.printStackTrace();
  					return null;
  				}
  			}
  			@SuppressWarnings("deprecation")
			protected void onPostExecute(BitmapDrawable bd) {
  				num = 1;
  				if (bd != null) {
  					photoRL1.setVisibility(View.GONE);
  					photoRL2.setVisibility(View.VISIBLE);
  					photoRL1.setBackgroundDrawable(bd);
				}	
			}
  		}.execute("");
  	}
  	//加载店铺图片
  	private void initLoadImage() {
  		new AsyncTask<String, Integer, BitmapDrawable>() {
  			@SuppressWarnings("deprecation")
			@Override
  			protected  BitmapDrawable doInBackground(String... params) {
  				BitmapDrawable bd;
  				try {
  					String url = ActionUrls.URL_SHOP_IMG + "?shopId="+shopId;
  					String json = HttpUtils.get(url, getAppCustomer().getHttpClient());
  					JSONObject jo = new JSONObject(json);
  					JSONObject jsonObject = jo.getJSONObject("shopImage");
  					DisplayMetrics dm = new DisplayMetrics();
					getWindowManager().getDefaultDisplay().getMetrics(dm);
					int displayWidth = dm.widthPixels;
					logoBitmap= getPic(ActionUrls.HOST_IMG+jsonObject.getString("fileName"));
					logoBitmap=change(logoBitmap, displayWidth);
  					bd = new BitmapDrawable(logoBitmap);
  					
  					return bd;
  				} catch (Exception e) {
  					e.printStackTrace();
  					return null;
  				}
  			}
  			@SuppressWarnings("deprecation")
			protected void onPostExecute(BitmapDrawable bd) {
  				if(num == 0){
  					if (bd != null) {
  	  					photoRL.setBackgroundDrawable(bd);
  	  				    photoRL1.setVisibility(View.GONE);
  	  				   
  	  				    
  					}
  					bd = null;
  				}
			}
  		}.execute("");
  	}
  	
  //设置图片高宽度
  	public static Bitmap change(Bitmap bmp,int displayWidth)    {
        int bmpWidth=bmp.getWidth(); 
        int bmpHeight=bmp.getHeight();
        displayWidth = 2*displayWidth;
        //获取图片原来的宽高比
        //double scale = Double.parseDouble(bmpWidth+"")/Double.parseDouble(bmpHeight+"");
        double scale = 1.6;
        //获取要显示的图片的高度
        double displayHeigth=displayWidth/scale;
       
        /* 产生reSize后的Bitmap对象 */
        Matrix matrix = new Matrix();
        float scaleWidth = Float.parseFloat(displayWidth+"")/bmpWidth;
        
        float scaleHeight = Float.parseFloat(displayHeigth+"")/bmpHeight;

        matrix.postScale(scaleWidth,scaleHeight);
      
        Bitmap resizeBmp = Bitmap.createBitmap(bmp,0,0,bmpWidth,bmpHeight,matrix,true); 
        bmp=null;
        return resizeBmp;
    }
    //加载图片
  	private void loadSetData() {
  		new AsyncTask<String, Integer, List<ImageVO>>() {

			@Override
  			protected  List<ImageVO> doInBackground(String... params) {
  			
  				try {
  					listSet = new ArrayList<ImageSetVo>();
  					DisplayMetrics dm = new DisplayMetrics();
  					getWindowManager().getDefaultDisplay().getMetrics(dm);
  					displayWidth = dm.widthPixels-40;
  					
  					List<ImageVO> images = loadSetImage();
  					
  					return images;
  				} catch (Exception e) {
  					e.printStackTrace();
  				}
  				return null;
  			}

  			
			protected void onPostExecute( List<ImageVO> images) {

  				tv_01.setText("");
				imgset_01.setImageBitmap(null);
				tv_01.setVisibility(View.GONE);
				imgset_01.setVisibility(View.GONE);
				tv_02.setText("");
				imgset_02.setImageBitmap(null);
				tv_02.setVisibility(View.GONE);
				imgset_02.setVisibility(View.GONE);
				tv_03.setText("");
				imgset_03.setImageBitmap(null);
				tv_03.setVisibility(View.GONE);
				imgset_03.setVisibility(View.GONE);
				tv_04.setText("");
				imgset_04.setImageBitmap(null);
				tv_04.setVisibility(View.GONE);
				imgset_04.setVisibility(View.GONE);
				ImageLoader imageLoader = ImageLoader.getInstance();
				
  				if (images != null && images.size()>0) {
	  				
  					for(int i=0;i<images.size();i++){
  						if(i==0){
  							tv_01.setText(images.get(0).getTitle());
  							imgset_01.setVisibility(View.VISIBLE);
  							imageLoader.displayImage(ActionUrls.HOST_IMG+images.get(0).getFilepath(), imgset_01, Options.getListOptions(),new SimpleImageLoadingListener() {

								@Override
								public void onLoadingStarted(String imageUri,
										View view) {
									ImageView iv =(ImageView)view;
									iv.setImageResource(R.drawable.logo);
									super.onLoadingStarted(imageUri, view);
								}

								@Override
								public void onLoadingComplete(String imageUri,
										View view, Bitmap loadedImage) {
									ImageView iv =(ImageView)view;
									iv.setImageBitmap(loadedImage);
									super.onLoadingComplete(imageUri, view, loadedImage);
								}
  								
  							});
  							tv_01.setVisibility(View.VISIBLE);
							
							
  						}else if(i==1){
  							tv_02.setText(images.get(1).getTitle());
  							imgset_02.setVisibility(View.VISIBLE);
  							imageLoader.displayImage(ActionUrls.HOST_IMG+images.get(1).getFilepath(), imgset_02, Options.getListOptions(),new SimpleImageLoadingListener() {

								@Override
								public void onLoadingStarted(String imageUri,
										View view) {
									ImageView iv =(ImageView)view;
									iv.setImageResource(R.drawable.logo);
									super.onLoadingStarted(imageUri, view);
								}

								@Override
								public void onLoadingComplete(String imageUri,
										View view, Bitmap loadedImage) {
									ImageView iv =(ImageView)view;
									iv.setImageBitmap(loadedImage);
									super.onLoadingComplete(imageUri, view, loadedImage);
								}
  								
  							});
  							tv_02.setVisibility(View.VISIBLE);
							
							
  						}else if(i==2){
  							tv_03.setText(images.get(2).getTitle());
  							imgset_03.setVisibility(View.VISIBLE);
  							imageLoader.displayImage(ActionUrls.HOST_IMG+images.get(2).getFilepath(), imgset_03, Options.getListOptions(),new SimpleImageLoadingListener() {

								@Override
								public void onLoadingStarted(String imageUri,
										View view) {
									ImageView iv =(ImageView)view;
									iv.setImageResource(R.drawable.logo);
									super.onLoadingStarted(imageUri, view);
								}

								@Override
								public void onLoadingComplete(String imageUri,
										View view, Bitmap loadedImage) {
									ImageView iv =(ImageView)view;
									iv.setImageBitmap(loadedImage);
									super.onLoadingComplete(imageUri, view, loadedImage);
								}
  								
  							});
  							tv_03.setVisibility(View.VISIBLE);
							
							
  						}else{
  							tv_04.setText(images.get(3).getTitle());
  							imgset_04.setVisibility(View.VISIBLE);
  							imageLoader.displayImage(ActionUrls.HOST_IMG+images.get(3).getFilepath(), imgset_04, Options.getListOptions(),new SimpleImageLoadingListener() {

								@Override
								public void onLoadingStarted(String imageUri,
										View view) {
									ImageView iv =(ImageView)view;
									iv.setImageResource(R.drawable.logo);
									super.onLoadingStarted(imageUri, view);
								}

								@Override
								public void onLoadingComplete(String imageUri,
										View view, Bitmap loadedImage) {
									ImageView iv =(ImageView)view;
									iv.setImageBitmap(loadedImage);
									super.onLoadingComplete(imageUri, view, loadedImage);
								}
  								
  							});
  							tv_04.setVisibility(View.VISIBLE);
							
							
  						}
  						
  					}
  					
  				}
  			}
  		}.execute("");
  	}
    private  List<ImageVO> loadSetImage() throws ClientProtocolException, IOException, JSONException {
  		String url = ActionUrls.URL_SHOP_SETIMG + "?shopId="+ getValue("shopId");
  		String json = HttpUtils.get(url, getAppCustomer().getHttpClient());
  		JSONObject jo = new JSONObject(json);
  		JSONArray ts = jo.getJSONArray("list");
  		List<ImageVO> list = JsonUtil.toShopImageVo(ts);
  		
  		return list;
  	}
    //加载logo图片
  	private void loadLogomage() {
  		if(getValue("headImage")!=null){
  			
  		}
  		new AsyncTask<String, Integer, BitmapDrawable>() {
  			@SuppressWarnings("deprecation")
			@Override
  			protected  BitmapDrawable doInBackground(String... params) {
  				BitmapDrawable bd=null;
  				try {
  					if (!"无".equals(getValue("headImage"))) {
  						logoBitmap = getPic(ActionUrls.HOST_IMG+getAppCustomer().getShop().getHeadImage());
						bd=new BitmapDrawable(logoBitmap); 
						if (logoBitmap != null && !logoBitmap.isRecycled()) 
	  					{ 
							logoBitmap=null;
	  					} 
  	  					return bd;
					}else {
						return null;
					}
  				} catch (Exception e) {
  					e.printStackTrace();
  				}
  				return null;
  			}
  			@SuppressWarnings("deprecation")
			protected void onPostExecute(BitmapDrawable bd) {
  				if (bd != null) {
  					img_01.setBackgroundDrawable(bd);
				}
			}

  		}.execute("");
  	}
	public Bitmap getPic(String uriPic) {
	    URL imageUrl = null;
	    Bitmap bitmap = null;
	    try {
	        imageUrl = new URL(uriPic);
	    } catch (MalformedURLException e) {
	        e.printStackTrace();
	    }
	    try {
	        HttpURLConnection conn = (HttpURLConnection) imageUrl.openConnection();
	        conn.connect();
	        int nRC = conn.getResponseCode();//得到连接状态
	        if(nRC == HttpURLConnection.HTTP_OK){
	        	BitmapFactory.Options options = new BitmapFactory.Options();

	        	options.inPreferredConfig = Config.ARGB_8888;

	        	options.inPurgeable = true;// 允许可清除

	        	options.inInputShareable = true;// 以上options的两个属性必须联合使用才会有效果
	        	InputStream is = conn.getInputStream();
		        bitmap = BitmapFactory.decodeStream(is, null, options);
		 
		        is.close();
	        }
	 
	    } catch (IOException e) {
	        e.printStackTrace();
	    }
	    return bitmap;
	}
	 /**监听对话框里面的button点击事件*/  
    DialogInterface.OnClickListener listener = new DialogInterface.OnClickListener()  
    {  
        public void onClick(DialogInterface dialog, int which)  
        {  
            switch (which)  
            {  
            case AlertDialog.BUTTON_POSITIVE:// "确认"按钮退出程序  
            	appExit();
                break;  
            case AlertDialog.BUTTON_NEGATIVE:// "取消"第二个按钮取消对话框  
                break;  
            default:  
                break;  
            }  
        }  
    };
    @SuppressWarnings("deprecation")
	@Override  
    public boolean onKeyDown(int keyCode, KeyEvent event)  
    {  
        if (keyCode == KeyEvent.KEYCODE_BACK )  
        {  
            // 创建退出对话框  
            AlertDialog isExit = new AlertDialog.Builder(this).create();  
            // 设置对话框标题  
            isExit.setTitle("系统提示");  
            // 设置对话框消息  
            isExit.setMessage("确定要退出吗");  
            // 添加选择按钮并注册监听  
            isExit.setButton2("取消", listener);  
            isExit.setButton("确定", listener);  
           
            // 显示对话框  
            isExit.show();  
  
        }  
          
        return false;  
          
    }  
    //获取店铺点赞和分享
  	private void initPraiseOrShare(){
  		new Thread() {
  			public void run() {
  				try {
  					
  					String json = HttpUtils.get(ActionUrls.URL_SHOP_GETPRAISEORSHARE+"?shopId="+getValue("shopId"),getAppCustomer().getHttpClient());
  					if(json!=null){
  						ShopVo shop = appc.getShop();
  						JSONObject jo = new JSONObject(json);
  						shop.setPraiseCount(jo.getString("praiseCount"));
  						shop.setShareCount(jo.getString("shareCount"));
  						shop.setExchangeToday(jo.getString("exchangeToday"));
  						shop.setTrackToday(jo.getString("trackToday"));
//  						save("praiseCount", jo.getString("praiseCount"));
//  						save("shareCount", jo.getString("shareCount"));
  						
  					}
  				} catch (ClientProtocolException e) {
  					e.printStackTrace();
  				} catch (IOException e) {
  					e.printStackTrace();
  				} catch (JSONException e) {
  					e.printStackTrace();
  				}
  			};
  		}.start();
  	}
  	
  	
}
